package ru.budget.mobile.data.sources.local

import ru.budget.mobile.core.Response
import ru.budget.mobile.core.ResponseStates
import ru.budget.mobile.data.entities.ConsumptionData
import ru.budget.mobile.data.sources.ConsumptionLocalSource
import ru.budget.mobile.data.sources.local.entities.ConsumptionDB
import ru.budget.mobile.data.sources.local.room.ConsumptionDAO

class ConsumptionLocalSourceImpl(
    private val dao: ConsumptionDAO
): ConsumptionLocalSource {
    override suspend fun consumptionList(): Response<List<ConsumptionData>> =
        try {
            val data = dao.consumptionList().map(mapper)

            if (data.isEmpty()) {
                throw Exception("Список полученный из базы данных пустой")
            } else {
                Response.Success(
                    data = data,
                    state = ResponseStates.SUCCESS
                )
            }
        } catch (exception: Exception) {
            Response.Error(
                exception = exception,
                state = ResponseStates.ERROR
            )
        }

    override suspend fun addConsumption(consumption: ConsumptionData): Response<Boolean> =
        try {
            val data = dao.addConsumption(
                consumption = ConsumptionDB(
                    id = consumption.id,
                    title = consumption.title,
                    type = consumption.type,
                    category = consumption.category,
                    sum = consumption.sum,
                    datetime = consumption.datetime
                )
            )
            if (data == -1L) {
                throw Exception("Не удалось добавить доход в базу данных")
            } else {
                Response.Success(
                    data = true,
                    state = ResponseStates.SUCCESS
                )
            }
        } catch (exception: Exception) {
            Response.Error(
                exception = exception,
                state = ResponseStates.ERROR
            )
        }

    private val mapper = { consumption: ConsumptionDB ->
        ConsumptionData(
            id = consumption.id,
            title = consumption.title,
            type = consumption.type,
            category = consumption.category,
            sum = consumption.sum,
            datetime = consumption.datetime
        )
    }
}